package org.ldh.web.servlet;

import org.ldh.service.UserService;
import org.ldh.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/otherServlet.action")
public class OtherServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("-----OtherServlet------");
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取请求参数
        String action = request.getParameter("action");
        System.out.println("action: "+action);

        if(action != null && action.equals("password")){
            //跳转到修改密码界面
            request.setAttribute("mainRight","/WEB-INF/pages/updatePassword.jsp");
            request.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(request,response);
        }else if(action != null && action.equals("rePassword")){
            //修改密码
            //获取请求参数
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //调用service层的修改方法
            UserService userService = new UserServiceImpl();
            userService.updatePassByName(username,password);
            //修改完成之后，跳转到修改页面，提示修改成功
            request.setAttribute("success","密码修改成功");
            request.setAttribute("mainRight","/WEB-INF/pages/updatePassword.jsp");
            request.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(request,response);
        }else if(action != null && action.equals("loginOut")){
            //退出登录
            //清除session中的用户信息
            request.getSession().removeAttribute("session_user");
            //清除cookie中的密码信息
            Cookie[] cookies = request.getCookies();
            if(cookies != null && cookies.length > 0){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals("remember")){
                        cookie.setMaxAge(0); //让密码失效
                    }
                }
            }
            //跳转到登录页面
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
